import 'dart:async';

import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class WaveformsWidget extends StatefulWidget {
  final String audioPath;
  final double width;
  final double waveformsHeight;
  final EdgeInsets padding;
  final EdgeInsets margin;
  final double radius;
  final Color bgColor;

  const WaveformsWidget({
    super.key,
    required this.audioPath,
    this.width = 200,
    this.waveformsHeight = 70,
    this.padding = const EdgeInsets.only(bottom: 6, right: 10, top: 6),
    this.margin = const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
    this.radius = 8,
    this.bgColor = const Color(0xFF25D4D0),
  });

  @override
  State<WaveformsWidget> createState() => _WaveformsWidgetState();
}

class _WaveformsWidgetState extends State<WaveformsWidget> {
  late PlayerController? controller;
  late StreamSubscription<PlayerState>? playerStateSubscription;
  late StreamSubscription<int>? playerDurationSubscription;
  final playerWaveStyle =
      const PlayerWaveStyle(fixedWaveColor: Colors.white54, liveWaveColor: Colors.white, spacing: 6);

  int totalDuration = 0;

  @override
  void initState() {
    super.initState();
    // clearController();
    // controller?.release();
    controller = PlayerController();
    _preparePlayer();
    playerStateSubscription = controller?.onPlayerStateChanged.listen((_) {
      totalDuration = controller!.maxDuration;
      logs('totalDuration = $totalDuration');
      setState(() {});
    });
    playerDurationSubscription = controller?.onCurrentDurationChanged.listen((int duration) {
      totalDuration = controller!.maxDuration - duration;
      setState(() {});
    });
  }

  void _preparePlayer() async {
    controller?.preparePlayer(path: widget.audioPath, shouldExtractWaveform: true);
    controller!
        .extractWaveformData(path: widget.audioPath, noOfSamples: playerWaveStyle.getSamplesForWidth(widget.width))
        .then((waveformData) => debugPrint(waveformData.toString()));
  }

  @override
  void dispose() {
    clearController();
    super.dispose();
  }

  void clearController() {
    try {
      playerStateSubscription?.cancel();
      playerDurationSubscription?.cancel();
      controller?.dispose();
    } catch (e) {
      logs(e.toString());
      //
    }
  }

  @override
  Widget build(BuildContext context) {
    return widget.audioPath.isEmpty
        ? const SizedBox.shrink()
        : Align(
            alignment: Alignment.center,
            child: Container(
              padding: widget.padding,
              margin: widget.margin,
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(widget.radius), color: widget.bgColor),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (!controller!.playerState.isStopped)
                    IconButton(
                      onPressed: () async {
                        controller!.playerState.isPlaying
                            ? await controller!.pausePlayer()
                            : await controller!.startPlayer();
                        controller!.setFinishMode(finishMode: FinishMode.pause);
                      },
                      icon: Icon(controller!.playerState.isPlaying ? Icons.stop : Icons.play_arrow),
                      color: Colors.white,
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                    ),
                  AudioFileWaveforms(
                    // size: Size(MediaQuery.of(context).size.width / 2, widget.waveformsHeight),
                    size: Size(widget.width, widget.waveformsHeight),
                    playerController: controller!,
                    waveformType: WaveformType.fitWidth,
                    // waveformType: WaveformType.long,
                    playerWaveStyle: playerWaveStyle,
                  ),
                  Container(
                      margin: const EdgeInsets.only(left: 10, right: 10),
                      child: Text('${((totalDuration / 1000).toStringAsFixed(0))}s',
                          style: TextStyle(color: Colors.white, fontSize: 13.sp, fontWeight: FontWeight.bold))),
                  // const SizedBox(width: 10),
                ],
              ),
            ),
          );
  }
}
